/*
 * @Description:
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-11-18 16:04:52
 * @LastEditors: kafei
 * @LastEditTime: 2021-11-18 17:16:36
 */
var mysql = require('mysql')
var connection = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'mymysql'
})
var query = function(sql, options, callback) {
  connection.getConnection(function(err, conn) {
    if (err) {
      callback(err, null, null)
    } else {
      conn.query(sql, options, function(err, results, fields) {
        // 事件驱动回调
        callback(err, results, fields)
      })
      // 释放连接，需要注意的是连接释放需要在此处释放，而不是在查询回调里面释放
      conn.release()
    }
  })
}

// 执行 sql 语句
var execSQL = function(sql) {
  const promise = new Promise((resolve, reject) => {
    query(sql, (err, result) => {
      if (err) {
        reject(err)
        return
      }
      resolve(result)
    })
  })
  return promise
}

module.exports = execSQL
